﻿using System;
using System.Web;
using HVACWebService.Cloud.WeChat;
using HVACWebService.Common;
using HVACWebService.DomainModel.WeiXin;

namespace HVACWebService.HtmlEntrance
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DoWith();
        }


        private void DoWith()
        {
   
            string appId = ConfigHelper.GetValue<string>("AppId");
            string appSecret = ConfigHelper.GetValue<string>("AppSecret");
            WeiXinOAuth weixinOAuth = new WeiXinOAuth();
       

            string _code = Request.QueryString["code"];
            string _state = Request.QueryString["state"];

            if (_code == "" || _code == "authdeny")
            {
                if (_code == "")
                {
                   
                    string _authUrl = weixinOAuth.GetWeiXinCode(appId, appSecret, HttpContext.Current.Server.UrlEncode(HttpContext.Current.Request.Url.ToString()));
                    HttpContext.Current.Response.Redirect(_authUrl, true);
                }
                else
                { 
                    HttpContext.Current.Response.Redirect("~/Error.html", true);
                }
            }
            else
            {

                try
                {
  
                    WeiXinAccessTokenResultModel modelResult = weixinOAuth.GetWeiXinAccessToken(appId, appSecret, _code);
                    if (modelResult.SuccessResult != null)
                    {
                        HttpCookie cookie = new HttpCookie("hvacUserInfo");
                        cookie.Values["openid"] = modelResult.SuccessResult.openid;
                        cookie.Values["accessToken"] = modelResult.SuccessResult.access_token;
                        cookie.Expires = System.DateTime.Now.AddDays(1);//设置过期时间  1天
                        Response.Cookies.Add(cookie);

                    }
                    else
                    {
                        HttpCookie cookie = new HttpCookie("hvacUserInfo");
                        cookie.Values["openid"] = "oct--vqUlmir4ieYHqwBsEEApylg";
                        cookie.Values["accessToken"] = "321";
                        cookie.Values["IsOpenAirFilter"] = "true";
                        cookie.Expires = DateTime.MaxValue;
                        //cookie.Expires = System.DateTime.Now.AddDays(1);//设置过期时间  1天
                        Response.Cookies.Add(cookie);

                    }

                    Response.Redirect("../HtmlPage/App_v1/index.html");

                }
                catch (Exception e)
                {
                  
                }
            
            }
        }


    }
}